﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using SQLiteCoreDB.Common;
using SQLiteCoreDB.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace SQLiteCoreDB.Context
{
    public class ChartApp : DbContext
    {
        private SQLiteContext db = new SQLiteContext();
        public DbSet<Login> Login { get; set; }

        public DbSet<ChatUser> ChatUser { get; set; }
        public DbSet<FileUser>? FileUser { get; set; }
        protected override async void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                if (!db.IsDBExists())
                {

                    var assembly = Assembly.GetExecutingAssembly();
                    var entityTypes = assembly.GetExportedTypes()
                        .Where(t => t.Namespace == typeof(Login).Namespace && !t.IsAbstract)
                        .ToList();

                    foreach (var entityType in entityTypes)
                    {
                        await db.Connection.CreateTableAsync(entityType);
                    }
                   

                    await db.AddAsync<Login>(new Login { id = 1, username = "admin", password = "123", role = "admin", LV = 1 });
                }


                string dbPath = KeyValueConfig.VN >1 ? KeyValueConfig.DBConnStr : SQLiteContext.DbPath ;
                optionsBuilder.UseSqlite($"Data Source={dbPath}");
            }
        }
    }
}

